package com.example.sample;

import com.ohos.volley.RequestQueue;
import com.ohos.volley.toolbox.ImageLoader;
import com.ohos.volley.toolbox.NetworkImageView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.TextField;

public class NetworkImageViewAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        super.setUIContent(ResourceTable.Layout_ability_network_image_view);

        TextField textField = (TextField) findComponentById(ResourceTable.Id_edit_url);
        Button runButton = (Button) findComponentById(ResourceTable.Id_button_run);
        NetworkImageView networkImageView = (NetworkImageView) findComponentById(ResourceTable.Id_network_image_view);

        RequestQueue queue = VolleyHelper.getInstance(this).getRequestQueue();
        LruImageCache lruImageCache = LruImageCache.instance();
        ImageLoader imageLoader = new ImageLoader(queue, lruImageCache);
        runButton.setClickable(true);
        runButton.setClickedListener(component -> {
            String url = textField.getText();
            loadInto(url, imageLoader, networkImageView);
        });
    }

    private void loadInto(String url, ImageLoader imageLoader, NetworkImageView networkImageView) {
        networkImageView.setDefaultImageResId(ResourceTable.Media_icon);
        networkImageView.setErrorImageResId(ResourceTable.Media_icon);
        networkImageView.setImageUrl(url, imageLoader);
    }
}
